package cn.com.tiptop.license.controller;

import java.io.File;
import java.util.Properties;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.alibaba.fastjson.JSON;

import cn.com.tiptop.comon.AjaxObject;
import cn.com.tiptop.comon.Code;
import cn.com.tiptop.license.entity.SecretKey;
import cn.com.tiptop.license.service.SecretKeyService;
import cn.com.tiptop.util.FileUtils;
import cn.com.tiptop.util.Md5Utils;
import cn.com.tiptop.util.MyResource;
import cn.com.tiptop.util.RSAUtils;

@Controller
@RequestMapping("/importProductInfo")
public class ImportProductInfo {
	
	@Resource
	private SecretKeyService secretKeyService;
	
	@SuppressWarnings("deprecation")
	@RequestMapping("/upload")
	@ResponseBody
	public AjaxObject image(String productInfo,@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request){
		String realpath = null;
		try{
			realpath = request.getRealPath("")+"WEB-INF"+File.separatorChar+"upload"
			+File.separatorChar+UUID.randomUUID().toString()+"_"+file.getOriginalFilename();
			System.out.println(realpath);
			File newFile = new File(realpath);
			file.transferTo(newFile);
			//获取产品号来定位解密私钥
			String productNumber = FileUtils.subtractMethodFile(realpath, 32);
			//获取私钥
			SecretKey secretKey  = null;//secretKeyService.getPrivateKeyByProductNumber(productNumber);
			if(secretKey!=null) {
				if(RSAUtils.RSADecodeFile(RSAUtils.getPrivateKey(secretKey.getPrivateKey()),newFile.getPath())) {
					String MD5 = FileUtils.subtractMethodFile(newFile.getPath(),32);
					String fMD5 = Md5Utils.fileMD5(newFile.getPath());
					if(MD5.equals(fMD5)) {
						Properties prop = MyResource.getProperties(realpath);
						if(prop.getProperty("PRODUCT_NUMBER", "").equals(productNumber)) {
							//TODO
							System.out.println(JSON.toJSONString(prop));
						}else {//产品号校验对不上
							newFile.delete();
							return new AjaxObject(Code.TRY_EXCEPTION,Code.getMsg(Code.TRY_EXCEPTION));
						}
						newFile.delete();
						return new AjaxObject(Code.REQUEST_SUCCESS,Code.getMsg(Code.REQUEST_SUCCESS));
					}
					newFile.delete();
					return new AjaxObject(Code.TRY_EXCEPTION,Code.getMsg(Code.TRY_EXCEPTION));
				}
			}
			//无产品私钥,非法产品
			newFile.delete();
			return new AjaxObject(Code.TRY_EXCEPTION,Code.getMsg(Code.TRY_EXCEPTION));
		}catch (Exception e) {
			e.printStackTrace();
			File f = new File(realpath);
			if(f.exists()) {
				f.delete();
			}
			return new AjaxObject(Code.TRY_EXCEPTION,Code.getMsg(Code.TRY_EXCEPTION));
		}
	}
}
